from PyQt5.QtCore import Qt
from PyQt5.QtGui import (QPainter, QColor, QPen)
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel)


class Example(QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUi()
        # 默认情况下禁用鼠标跟踪， 如果启用鼠标跟踪，即使没有按钮被按下，小部件也会接收鼠标移动事件。
        # 当然你也可以不写，只需要在执行的过程中按照鼠标左键也行
        self.setMouseTracking(True)

    def initUi(self):
        self.setGeometry(400, 300, 400, 300)
        self.setWindowTitle("键盘响应事件")
        self.lab1 = QLabel("方向", self)
        self.lab1.setGeometry(200, 150, 100, 100)
        self.lab2 = QLabel("显示鼠标坐标", self)
        self.lab2.setGeometry(200, 80, 100, 100)

    """重定义键盘事件"""

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Up:
            self.lab1.setText("↑")
        elif e.key() == Qt.Key_Down:
            self.lab1.setText("↓")
        elif e.key() == Qt.Key_Left:
            self.lab1.setText("←")
        else:
            self.lab1.setText("→")

    """重定义鼠标单击事件"""

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.lab1.setText("鼠标左键点击！")
            # print(event.pos().x(),event.pos().y())
        if event.button() == Qt.RightButton:
            self.lab1.setText("鼠标右键点击！")

    """当鼠标左键点击拖动时触发事件,有无if判断条件效果都一样"""

    def mouseMoveEvent(self, event):
        # if event.buttons() == Qt.LeftButton:
        #     # print(type(event.pos().x()))    #<class 'int'>
        #     self.lab2.setText(str(event.pos().x())+","+str(event.pos().y()))
        self.pos = event.pos()
        print(self.pos)
        self.lab2.setText(str(event.pos().x()) + "," + str(event.pos().y()))
        self.update()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())
